//
//  JSDSportType.m
//  仿咕咚
//
//  Created by Abner on 16/11/8.
//  Copyright © 2016年 Abner. All rights reserved.
//

#import "JSDSportTracking.h"
#import "JSDSportTrackingLine.h"

@interface JSDSportTracking ()
@property(nonatomic,strong) NSMutableArray<JSDSportTrackingLine *> *trackingLineArrM;
@end
@implementation JSDSportTracking{
    CLLocation *_startLocation;
}

- (instancetype)initWithType:(JSDSportType)type states:(JSDSportState)state{
    self = [super init];
    if (self) {
        _sportType = type;
        _sportState = state;
        _trackingLineArrM = [NSMutableArray array];
    }
    return self;
}
- (NSString *)imageStr{
    switch (_sportType) {
        case JSDSportTypeRun:
            return @"map_annotation_run";
            break;
        case JSDSportTypeWalk:
            return @"map_annotation_walk";
            break;

        case JSDSportTypeRiding:
            return @"map_annotation_bike";
            break;
    }
}
- (MAPolyline *)appendLocation:(CLLocation *)location{
    if (_sportState != JSDSportStateContinue) {
        return nil;
    }
    if (_startLocation == nil) {
        _startLocation = location;
        return nil;
    }
    //初次定位不准确，根据时间戳判断，解决杂线问题
    CGFloat factor = 2;
    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] > factor) {
        return  nil;
    }
    if (location.speed <= 0) {
        return nil;
    }
    //实例化轨迹模型
    JSDSportTrackingLine *trackingLine = [[JSDSportTrackingLine alloc] initWithStartLocation:_startLocation endLocation:location];
    [_trackingLineArrM addObject:trackingLine];
    trackingLine.speed = location.speed;
    MAPolyline *polyLine = trackingLine.polyLine;
    _startLocation = location;
    return polyLine;
}
///利用KVC汇总数据
- (double)avgSpeed{
    return [[_trackingLineArrM valueForKeyPath:@"@avg.speed"] doubleValue];
}
- (double)maxSpeed{
    return [[_trackingLineArrM valueForKeyPath:@"@max.speed"] doubleValue];
}
- (double)totalTime{
    return [[_trackingLineArrM valueForKeyPath:@"@sum.time"] doubleValue];
}
- (double)totalDistance{
    return [[_trackingLineArrM valueForKeyPath:@"@sum.distance"] doubleValue];
}
-(void)setSportState:(JSDSportState)sportState{
    _sportState = sportState;
    //清空起点，防止模拟器点击继续时会从当前位置拉直线到暂停位置；
    if (sportState != JSDSportStateContinue) {
        _startLocation = nil;
    }
}
@end
